<template>
  <div class="post-container">
    <div class="post-content">
      <h2>发布帖子</h2>
      
      <el-form
        ref="postFormRef"
        :model="postForm"
        :rules="postRules"
        label-position="top"
      >
        <el-form-item label="标题" prop="title">
          <el-input
            v-model="postForm.title"
            placeholder="请输入帖子标题（2-100个字符）" 
            maxlength="100" 
            show-word-limit
          />
        </el-form-item>
        
        <el-form-item label="内容" prop="content">
          <el-input
            v-model="postForm.content"
            type="textarea"
            :rows="8"
            placeholder="请输入帖子内容（至少10个字符）" 
            maxlength="5000"
            show-word-limit
          />
        </el-form-item>
        
        <el-form-item label="话题" prop="tags"> 
          <el-select
            v-model="postForm.tags" 
            multiple
            filterable
            allow-create
            default-first-option
            placeholder="选择或创建话题（最多5个）"
            :max-collapse-tags="3"
          >
            <el-option
              v-for="topic in hotTopics"
              :key="topic"
              :label="topic"
              :value="topic"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="分类" prop="category">
          <el-select
            v-model="postForm.category"
            placeholder="请选择帖子分类"
          >
            <el-option
              v-for="category in categories"
              :key="category._id"
              :label="category.name"
              :value="category._id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="图片">
          <el-upload
            v-model:file-list="fileList" 
            class="post-uploader"
            action="#" 
            list-type="picture-card"
            :auto-upload="false"
            :on-change="handleImageChange"
            :on-remove="handleImageRemove"
            :limit="9"
            accept="image/*"
          >
            <el-icon><Plus /></el-icon>
            <template #tip>
              <div class="upload-tip">支持 JPG/PNG 等图片格式，单张不超过 5MB，最多上传9张</div> 
            </template>
          </el-upload>
        </el-form-item>
        
        <div class="form-actions">
          <el-button @click="saveDraft" :loading="isSavingDraft">保存草稿</el-button> 
          <el-button type="primary" @click="submitPost" :loading="isSubmitting">
            发布
          </el-button>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import axios from '@/services/axios'
import * as categoryService from '@/services/categoryService'; // 导入 categoryService

const router = useRouter()
const postFormRef = ref(null)
const isSubmitting = ref(false)
const isSavingDraft = ref(false)
const fileList = ref([])
const categories = ref([]); // 新增 categories 数组

// 表单数据
const postForm = reactive({
  title: '',
  content: '',
  tags: [],
  category: '', // 新增 category 字段
})

// 表单验证规则
const postRules = {
  title: [
    { required: true, message: '请输入标题', trigger: 'blur' },
    { min: 2, max: 100, message: '标题长度应在2-100个字符之间', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入内容', trigger: 'blur' },
    { min: 10, message: '内容至少10个字符', trigger: 'blur' }
  ],
  tags: [
    { type: 'array', max: 5, message: '最多选择5个话题', trigger: 'change' }
  ],
  category: [
    { required: true, message: '请选择分类', trigger: 'change' }
  ]
}

// 热门话题列表
const hotTopics = ref([
  '生活', '美食', '旅行', '电影', '音乐',
  '游戏', '动漫', '科技', '运动', '宠物'
])

// 获取热门话题
const fetchHotTopics = async () => {
  try {
    const response = await axios.get('/api/topics/hot')
    hotTopics.value = response.data
  } catch (error) {
    console.error('获取热门话题失败:', error)
  }
}

// 获取分类列表
const fetchCategories = async () => {
  try {
    const response = await categoryService.getCategories();
    categories.value = response.data;
  } catch (error) {
    console.error('获取分类失败:', error);
  }
};

// 发布帖子
const submitPost = async () => {
  if (!postFormRef.value) return

  await postFormRef.value.validate(async (valid) => {
    if (valid) {
      isSubmitting.value = true
      
      try {
        const formData = new FormData()
        formData.append('title', postForm.title)
        formData.append('content', postForm.content)
        formData.append('tags', JSON.stringify(postForm.tags))
        formData.append('category', postForm.category); // 添加 category 字段
        formData.append('isDraft', false); // 修改为布尔值 false
        
        // 添加图片文件
        fileList.value.forEach(file => {
          if (file.raw) {
            formData.append('images', file.raw)
          }
        })
        
        const response = await axios.post('/api/posts', formData, {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        })
        
        ElMessage.success('帖子发布成功')
        router.push(`/post/${response.data.post._id}`)
      } catch (error) {
        console.error('发布失败:', error)
        ElMessage.error(error.response?.data?.error || '发布失败，请稍后重试')
      } finally {
        isSubmitting.value = false
      }
    } else {
      ElMessage.error('请检查表单信息是否完整')
    }
  })
}

// 保存草稿
const saveDraft = async () => {
  if (!postFormRef.value) return

  await postFormRef.value.validateField('title', async (isValid) => {
    if (isValid) {
      isSavingDraft.value = true
      try {
        const formData = new FormData()
        formData.append('title', postForm.title)
        formData.append('content', postForm.content)
        formData.append('tags', JSON.stringify(postForm.tags))
        formData.append('category', postForm.category); // 添加 category 字段
        formData.append('isDraft', true); // 保存草稿时为 true

        // 添加图片文件
        fileList.value.forEach(file => {
          if (file.raw) {
            formData.append('images', file.raw)
          }
        })

        await axios.post('/api/posts', formData, {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        })
        ElMessage.success('草稿保存成功')
      } catch (error) {
        console.error('保存草稿失败:', error)
        ElMessage.error(error.response?.data?.error || '保存草稿失败，请稍后重试')
      } finally {
        isSavingDraft.value = false
      }
    } else {
      ElMessage.warning('请输入标题以保存草稿')
    }
  })
}

onMounted(() => {
  fetchHotTopics();
  fetchCategories(); // 在组件挂载时获取分类列表
});
</script>

<style scoped>
.post-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.post-content {
  background: #fff;
  padding: 24px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

h2 {
  margin-top: 0;
  margin-bottom: 24px;
  font-size: 24px;
  font-weight: 500;
  color: #303133;
}

.form-actions {
  margin-top: 24px;
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.post-uploader {
  :deep(.el-upload--picture-card) {
    width: 120px;
    height: 120px;
    line-height: 120px;
  }
}

.upload-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 8px;
}
</style>
.post-content h2 {
  text-align: center;
  margin-bottom: 30px;
  font-size: 24px;
  color: #303133;
}

.el-form-item {
  margin-bottom: 25px;
}

.el-select {
    width: 100%;
}

.post-uploader :deep(.el-upload--picture-card) {
  width: 100px;
  height: 100px;
}

.post-uploader :deep(.el-upload-list--picture-card .el-upload-list__item) {
  width: 100px;
  height: 100px;
}

.upload-tip {
  color: #909399;
  font-size: 12px;
  margin-top: 5px;
}

.form-actions {
  text-align: right;
  margin-top: 30px;
}

.form-actions .el-button {
  margin-left: 10px;
}
